package com.example.publishdemo.publishservice;

import com.example.publishdemo.publishservice.enums.PublishServicesType;
import com.example.publishdemo.publishservice.event.MyPublishEventForAsync;
import com.example.publishdemo.publishservice.event.MyPublishEventForSync;
import com.example.publishdemo.publishservice.exception.MyPublishException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

@Component
public class PublishAware implements ApplicationEventPublisherAware {


    //注册发布者套件，可以理解为固定流程
    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }


    /**
     * 自定义发布流程，比如记录日志，又比如数据统一格式转换
     * （总之是发布流程开始工作之前，所要做的统一流程）
     * 参数自定义，毕竟这是自定义函数
     * 传入参数可以定义基本类别，然后各个服务通过继承该父类，
     * 实现向上转型，当流程走到集体转发服务是，
     * 再通过向下转型，实现参数的统一和自定义实现
     *
     *
     * 异步发布消息
     *
     * @param message
     * @param publishServicesType
     */
    public void publishProcessForAsync(String message, PublishServicesType publishServicesType) {
        System.out.println("开始放消息在懒惰的发布员的信箱中");
        //我想要在所有发布的消息上加上publisher：
        String msg = "publisher：" + message;
        try {

            publisher.publishEvent(new MyPublishEventForAsync(this, publishServicesType, msg));
        } catch (Exception e) {
            throw new MyPublishException("发布者出现错误了，请求紧急支援！！！！！！！！！！！！！");
        }

    }

    /**
     * 同步发布消息
     *
     * @param message
     * @param publishServicesType
     */
    public void publishProcessForSync(String message, PublishServicesType publishServicesType) {
        System.out.println("开始放消息在勤快的发布员的信箱中");
        //我想要在所有发布的消息上加上publisher：
        String msg = "publisher：" + message;
        try {
            publisher.publishEvent(new MyPublishEventForSync(this, publishServicesType, msg));
        } catch (Exception e) {
            throw new MyPublishException("发布者出现错误了，请求紧急支援！！！！！！！！！！！！！");
        }

    }

}
